<!--
 * @description  : 检查（勘验）笔录动态模板
 * @descriptionDetail: 检查（勘验）笔录动态模板
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-10-31 10:57:44
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :is-white="true" :title="navTitle" :custom-back="goBack" style="z-index: 99999">
      <view class="theme-color" @click="handlerSure()">
        确认
      </view>
    </theme-navbar>
    <!-- #endif -->
		<!-- #ifdef H5-WECHAT || H5-EMP -->
		<fab-button :content="fContent" @fabtrigger="fabtrigger" />
		<!-- #endif -->
    <!-- 表单开始 -->
    <view class="main-content">
      <u-form ref="uForm">
        <u-form-item label="模板类型" right-icon="arrow-right" :label-width="labelWidth">
          <u-input placeholder="请选择" :disabled="true" v-model="moduleObj.label" @click="()=>{isShowModule = true}" />
          <u-select mode="single-column" :list="moduleList" v-model="isShowModule" @confirm="selectConfirm"></u-select>
        </u-form-item>
      </u-form>
      <u-form class="form-content" ref="freeForm">
        <view v-for="(item, idx) in freeForm" :key="idx">
          <!-- 第一层自由表单 -->
          <view v-if="item.eleType == 'checkbox' && !item.parentField">
            <u-form-item :label="item.formShowName" :label-position="labelPosition">
              <u-checkbox-group :wrap="true">
                <u-checkbox
                  :name="opt.id"
                  shape="square"
                  v-for="(opt, index) in item.options"
                  :key="index"
                  v-model="opt.checked"
                  @change="checkboxChange($event,item.fieldName,opt.name)"
                >
                  {{ opt.name }}
                </u-checkbox>
              </u-checkbox-group>
            </u-form-item>
          </view>
          <view v-else-if="item.eleType == 'radio' && !item.parentField">
            <u-form-item :label="item.formShowName" :label-position="labelPosition">
              <u-radio-group :wrap="true" v-model="checkObj[item.fieldName]">
                <u-radio
                  :name="opt.name"
                  v-for="(opt, index) in item.options"
                  :key="index"
                  @change="radioChange(opt.id,item.fieldName,opt.name)"
                >
                  {{ opt.name }}
                </u-radio>
              </u-radio-group>
            </u-form-item>
          </view>
          <view v-else-if="item.eleType == 'textarea' && !item.parentField">
            <u-form-item :label="item.formShowName" :label-position="labelPosition">
              <u-input
                type="textarea"
                placeholder="请填写"
                height="100"
                :auto-height="true"
                v-model="checkObj[item.fieldName]"
              />
            </u-form-item>
          </view>
          <view v-else-if="(item.eleType == 'input' || item.eleType == '') && !item.parentField">
            <u-form-item :label="item.formShowName" :label-position="labelPosition">
              <u-input placeholder="请输入" v-model="checkObj[item.fieldName]" />
            </u-form-item>
          </view>
          <!-- 第二层联动表单 -->
          <view class="indent-sty" v-show="checkObj['prt'+item.parentField+item.parentValue]">
            <u-card :title="item.formShowName">
              <view class="" slot="body">
                <view class="u-body-item u-flex u-border-bottom u-col-between u-p-t-0">
                  <view class="u-body-item-title u-line-2">
                    <!-- 复选框 -->
                    <view v-if="item.eleType == 'checkbox'">
                      <u-checkbox-group :wrap="true">
                        <u-checkbox
                          :name="opt.id"
                          shape="square"
                          v-for="(opt, index) in item.options"
                          :key="index"
                          v-model="opt.checked"
                          @change="checkboxChange($event,item.fieldName,opt.name,item.parentField,item.parentValue)"
                        >
                          {{ opt.name }}
                        </u-checkbox>
                      </u-checkbox-group>
                    </view>
                    <!-- 单选框 -->
                    <view v-else-if="item.eleType == 'radio'">
                      <u-radio-group :wrap="true" v-model="checkObj[item.fieldName]">
                        <u-radio
                          :name="opt.name"
                          v-for="(opt, index) in item.options"
                          :key="index"
                          @change="radioChange(opt.id,item.fieldName,opt.name,item.parentField,item.parentValue)"
                        >
                          {{ opt.name }}
                        </u-radio>
                      </u-radio-group>
                    </view>
                    <!-- 文本域 -->
                    <view v-else-if="item.eleType == 'textarea'">
                      <u-field
                        type="textarea"
                        label-width="1"
                        label=""
                        placeholder="请输入"
                        style="height: 60px;"
                        :auto-height="true"
                        :border-bottom="false"
                        v-model="checkObj[item.fieldName]"
                        @blur="handleBlur(item.fieldName,item.parentField,item.parentValue)"
                      >
                      </u-field>
                    </view>
                    <!-- 输入框 -->
                    <view v-else>
                      <u-input placeholder="请输入" v-model="checkObj[item.fieldName]" @blur="handleBlur(item.fieldName,item.parentField,item.parentValue)" />
                    </view>
                  </view>
                </view>
              </view>
            </u-card>
          </view>
        </view>
      </u-form>
    </view>
  </view>
</template>

<script>
	import caseService from "@/service/case/case.service";
	import officeService from "@/service/case/office.service.js";
	import fabButton from '@/components/uni-fab.vue';

	export default {
		components: {
			fabButton
		},
		data() {
			return {
				labelWidth: '220',
				labelPosition: 'top',
				moduleParam: {}, // 获取模板list参数
				moduleList: [], // 模板数据
				moduleObj: {}, // 默认模板
				isShowModule: false,
				itemJson: {}, // 自由表单数据
				mainLabelStyle: {
					'fontWeight': '600',
				},
				freeForm: [],
				checkObj: {},
				linkageData: {}, // 组装联动数据
				showContent: "案发日期，我局执法人员一行{{checkObj.peopleCount}}人checkType ，在出示检查证件，表明身份，说明来意后，依法对位于案发地点被检查的当事人的经营场所（|specificLocation|）实施检查。&&执法人员当场在当事人经营场所（|specificLocation|）的|specificLocatio2|内查获涉嫌案由的卷烟多个卷烟条码等共计涉案物品个数个品规，涉案物品数量条。其中 |theCigarette|，查获时，|seizedSituation|&&因当事人涉嫌 案由，根据《中华人民共和国行政处罚法》第五十六条规定，经局领导批准，我局执法人员在 |checkPeople||peopleName|对先行登记保存卷烟的数量品种清点无误后，当场将上述卷烟用 |tool|装好并在其上下可封口处加贴存条予以先行登记保存（具体品牌数量详见先行登记保存通知书NO.  先保书文书号）。同时，执法人员现场拍摄了照片。 &&查获时，被检查人被检查人是否在场案发现场。被检查人及现场相关人员的人身因本局执法人员的检查|peopleInjury|伤害，经营场所|specificLocation|的财物因本局执法人员的检查|cigaeInjury|损坏。",
				fContent: [{
					iconPath: require('@/static/confirm.png'),
					selectedIconPath: require('@/static/confirm.png'),
					text: '确定',
					active: false,
				}],
			}
		},
		onLoad(preParams) {
			this.moduleParam = this.getRouteParam();
		},
		mounted() {
			this.setRightBtns();
			this.init();
		},
		methods: {
			setRightBtns() {
				// 设置右侧标题
				let self = this;
				// #ifdef H5-DINGDING
				this.$deviceApi.setRight("确定", () => {
					self.handlerSure();
					self.setRightBtns();
				}, true, true);
				// #endif
			},
			fabtrigger(btn) {
				if (btn.index == 0) {
					this.handlerSure();
				}
			},
			// 初始化加载模板
			init() {
				this.moduleList = [];
				this.$modal.showLoading('加载中...');
				caseService.findFieldDefaults(this.moduleParam).then(res => {
					this.$modal.hideLoading();
					if (res.success) {
						let list = res.data ? res.data : [];
						list.forEach((item) => {
							let opt = {
								value: item.moduleUuid,
								label: item.moduleName,
							}
							this.moduleList.push(opt);
						})
						if (this.moduleList.length > 0) {
							this.moduleObj = this.moduleList[0];
							this.getFreeForm();
						}
					} else {
						this.$u.toast(res.msg);
					}
				});
			},
			// 模板选择确认事件
			selectConfirm(e) {
				if (e.length > 0) {
					this.moduleObj = e[0];
					this.freeForm = {};
					this.getFreeForm();
				}
			},
			// 获取自由表单数据
			getFreeForm() {
				let freeParam = {
					...this.moduleParam,
				};
				freeParam.moduleUuid = this.moduleObj.value;
				this.$u.loading('加载中...');
				officeService.findDocFreeFormInfo(freeParam).then((res) => {
					this.$u.hideLoading();
					if (res.success) {
						this.itemJson = res.bean;
						this.freeForm = JSON.parse(JSON.stringify(this.itemJson.list));
						this.getLinkageData();
					} else {
						this.$u.toast(res.msg);
					}
				});
			},
			// 组装联动数据
			getLinkageData() {
				this.linkageData = {};
				if (this.freeForm && this.freeForm.length > 0) {
					this.freeForm.forEach((item) => {
						if (item.parentField && item.parentValue) {
							this.linkageData[item.parentField + item.parentValue] = this.linkageData[item.parentField + item.parentValue] ? this.linkageData[item.parentField + item.parentValue] : [];
							this.linkageData[item.parentField + item.parentValue].push(item);
						}
						// 初始化获取默认值
						if (item.defaultVal) {
							this.checkObj[item.fieldName] = item.defaultVal;
						}
						if (item.options && item.options.length > 0) {
							item.options.forEach((opt) => {
								if (opt.defaultValue) {
									if (item.eleType == 'checkbox') {
										opt.checked = true;
										this.checkObj[item.fieldName] = this.checkObj[item.fieldName] ? this.checkObj[item.fieldName] : [];
										this.checkObj[item.fieldName].push(opt.name);
									} else if (item.eleType == 'radio') {
										this.checkObj[item.fieldName] = opt.name;
									}
								}
							})
						}
					});
				}
				console.log(this.linkageData);
			},
			// 复选框事件 e:{value:true,name:'2'}
			checkboxChange(e, fieldName, name, parentField, parentValue) {
				this.checkObj[fieldName] = this.checkObj[fieldName] ? this.checkObj[fieldName] : [];
				if (this.checkObj[fieldName].length > 0) {
					// 勾选
					if (e.value) {
						if (this.checkObj[fieldName].join(',').indexOf(name) == -1) {
							this.checkObj[fieldName].push(name);
							this.checkObj['prt' + fieldName + e.name] = true;
						}
					} else {
						// 取消
						this.checkObj[fieldName].forEach((item, ind) => {
							if (item == name) this.checkObj[fieldName].splice(ind, 1);
						});
						this.checkObj['prt' + fieldName + e.name] = false;
					}
				} else {
					this.checkObj[fieldName].push(name);
					this.checkObj['prt' + fieldName + e.name] = true;
				}
				// 给父级文本赋值
				this.replaceParentTxt(fieldName, parentField, parentValue);
				// console.log(this.checkObj);
			},
			// 单选框事件
			radioChange(id, fieldName, name, parentField, parentValue) {
				// 设置勾选的值并显示下级内容
				this.checkObj[fieldName] = name;
				this.checkObj['prt' + fieldName + id] = true;

				// 勾选值以外的下级隐藏
				let fieldList = this.itemJson.list.filter((item) => {
					return item.fieldName == fieldName;
				});
				if (fieldList.length > 0) {
					fieldList[0].options.forEach((opt) => {
						if (id != opt.id) this.checkObj['prt' + fieldName + opt.id] = false;
					});
				}
				// console.log(this.checkObj);
				this.$forceUpdate();
				// 给父级赋值
				this.replaceParentTxt(fieldName, parentField, parentValue);
			},
			// 文本框、文本域
			handleBlur(fieldName, parentField, parentValue) {
				this.replaceParentTxt(fieldName, parentField, parentValue);
			},
			// 替换父级文本内容
			replaceParentTxt(fieldName, parentField, parentValue) {
				// 给父级文本替换值
				if (parentField && parentValue) {
					let fieldList = this.itemJson.list.filter((item) => {
						return item.fieldName == parentField;
					});
					// 根据父级Field和Value，找到对应的option的name
					let tx = fieldList.length > 0 ? fieldList[0].options[Number(parentValue) - 1].name : '';
					if (tx) {
						for (let k in this.checkObj) {
							if (tx.indexOf('|' + k + '|') != -1 && this.checkObj[k]) {
								tx = tx.replace(new RegExp(k, 'g'), this.checkObj[k]);
							}
						}
						// 替换表单展示项的值
						this.freeForm.forEach((free) => {
							if (free.fieldName == parentField) {
								if (tx.indexOf('|') != -1) {
									tx = tx.replace(/\|/g, '');
								}
								free.options[Number(parentValue) - 1].name = tx;
								if (free.eleType == 'radio') {
									this.checkObj[parentField] = tx;
								}
							}
						})
					}
				}
			},
			// 确认
			handlerSure() {
				// console.log(this.checkObj);
				// 替换预览文本内容的key
				let content = this.itemJson.content;
				for (let k in this.checkObj) {
					content = content.replace(new RegExp(k, 'g'), this.checkObj[k]);
				}
				if (content.indexOf('|') != -1) {
					content = content.replace(/\|/g, '');
				}
				// console.log(content);
				this.backPrev({
					paramKey: "localDesc",
					param: content,
				});
			},
		},
	}
</script>

<style lang="scss" scoped>
	@import "../case_common.scss";

	.indent-sty {
		margin-left: 20px;
	}

	/deep/ .u-checkbox {
		margin-bottom: 6px;
	}
</style>
